<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Db;
use think\Session;

class Login extends Controller
{
    public function index()
    {
        return view('Login/login');
    }

    public function dologin(Request $request)
    {
        $adminuser = $request->post();

        $data = Db::name('lamp_user')
            ->where('username', $adminuser['name'])
            ->find();

        if(!$data){
            $this->error('用户名不存在');
            exit;
        }

        if($data['userpass'] != md5($adminuser['pass'])){
            $this->error('密码不正确');
            exit;
        }

       Session::set('admin_user', $data, 'think');

        $query = Db::table('lamp_user_role')
                ->field('rid')
                ->where('uid', $data['id'])
                ->fetchSql(true)
                ->select();

        $query2 = Db::table('lamp_role_node')
                    ->field('nid')
                    ->join('('.$query.') ur', 'ur.rid=lamp_role_node.rid')
                    ->fetchSql(true)
                    ->select();

        $list = Db::table('node')
                ->field(['mname', 'aname'])
                ->join('('.$query2.') rn', 'rn.nid=node.id')
                ->select();

        foreach($list as $k=>$v){
            $list[$k]['mname'] = ucfirst($v['mname']);
        }
//        var_dump($list);die;

        $nodelist = [];
        $nodelist['Index'] = ['index'];

        foreach($list as $v){
            $nodelist[$v['mname']][] = $v['aname'];

            if($v['aname']=="edit"){
                $nodelist[$v['mname']][]="save";
            }
            if($v['aname']=="add"){
                $nodelist[$v['mname']][]="doadd";
            }
        }

//        var_dump($nodelist); die;
        //将权限信息放置到session中
        Session::set('admin_user.nodelist', $nodelist, 'think');

        $this->redirect('admin/Index/index');
    }

    public function nologin()
    {
        //清空session
        Session::delete('admin_user', 'think');
        //跳转
        $this->redirect('admin/Index/index');
    }
}
